#include "jpanelfactory.h"
#include <QTECore/jlog.h>

namespace QTE
{

template <class T>
static T *createObject(const QByteArray &className)
{
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
	int typeID = QMetaType::type(className);

	if( typeID <= 0 )
	{
		jWarning() << QString("JInputPanelFactory: The type is not register. (%1)").arg(QString::fromLocal8Bit(className));
		return nullptr;
	}
	auto obj = QMetaType::metaObjectForType(typeID)->newInstance();
#else

	auto metaType = QMetaType::fromName(className);

	if( not metaType.isValid() )
	{
		jWarning() << QString("JInputPanelFactory: The type is not register. (%1)").arg(QString::fromLocal8Bit(className));
		return nullptr;
	}
	auto obj = metaType.metaObject()->newInstance();
#endif

	if( obj == nullptr )
	{
		jWarning() << QString("JInputPanelFactory: Object construction failure. (%1)").arg(QString::fromLocal8Bit(className));
		return nullptr;
	}

	auto panel = J_OCT(T*, obj);
	if( panel == nullptr )
		jWarning() << QString("JInputPanelFactory: The object type conversion failed. (%1)").arg(QString::fromLocal8Bit(className));
	return panel;
}

JAbstractCandidatePanel *JPanelFactory::createCandidatePanel(Language language)
{
	return createObject<JAbstractCandidatePanel>(CandidatePanelClassName(language));
}

JAbstractInputPanel *JPanelFactory::createInputPanel(Language language)
{
	return createObject<JAbstractInputPanel>(InputPanelClassName(language));
}

JAbstractInputPanel *JPanelFactory::createSymbolPanel(Language language)
{
	return createObject<JAbstractInputPanel>(SymbolPanelClassName(language));
}

} //namespace QTE
